<template>
  <div class="carousel-add">
    <div class="page-header">
      <h2>新增轮播图</h2>
      <p>添加首页轮播图内容</p>
    </div>

    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        class="carousel-form"
        label-position="left"
        size="large"
      >
        <el-form-item label="轮播图标题" prop="title" required>
          <el-input
            v-model="formData.title"
            placeholder="请输入..."
            maxlength="50"
            show-word-limit
            style="width: 400px"
          />
        </el-form-item>
        
        <el-form-item label="轮播图" prop="imageUrl" required>
          <div class="upload-section">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :headers="{ 'Accept': 'application/json' }"
              accept="image/*"
              drag
            >
              <img v-if="formData.imageUrl" :src="formData.imageUrl" class="uploaded-image" />
              <div v-else class="upload-area">
                <el-icon class="upload-icon"><Plus /></el-icon>
              </div>
            </el-upload>
            <div class="upload-hint">
              建议尺寸375*211，不要超过1M
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="轮播图状态" prop="status" required>
          <el-switch
            v-model="formData.status"
            size="large"
            :active-value="true"
            :inactive-value="false"
            active-color="#409EFF"
          />
        </el-form-item>
        
        <el-form-item label="生效开始时间" prop="effectiveStartTime">
          <el-date-picker
            v-model="formData.effectiveStartTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 400px"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="生效结束时间" prop="effectiveEndTime">
          <el-date-picker
            v-model="formData.effectiveEndTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 400px"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="轮播图链接地址" prop="linkUrl" required>
          <el-input
            v-model="formData.linkUrl"
            placeholder="请输入..."
            style="width: 400px"
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="sortOrder" required>
          <div class="sort-section">
            <el-input-number
              v-model="formData.sortOrder"
              :min="1"
              :max="999"
              placeholder="请输入..."
              style="width: 400px"
              controls-position="right"
            />
            <div class="sort-hint">
              填写数字，数字越大越靠前
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div class="form-actions">
        <el-button size="large" @click="handleCancel">取消</el-button>
        <el-button type="primary" size="large" @click="handleSubmit" :loading="submitLoading">
          提交
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { carouselApi } from '@/api/index'
import type { CarouselItem } from '@/api/index'
import { Plus } from '@element-plus/icons-vue'

/**
 * 轮播图添加页面
 * 按照用户提供的设计图实现
 */

const router = useRouter()
const formRef = ref()
const submitLoading = ref(false)

// 表单数据接口
interface FormData {
  title: string
  imageUrl: string
  status: boolean
  linkUrl: string
  sortOrder: number
  effectiveStartTime: string
  effectiveEndTime: string
}

// 表单数据
const formData = reactive<FormData>({
  title: '',
  imageUrl: '',
  status: true,
  linkUrl: '',
  sortOrder: 1,
  effectiveStartTime: '',
  effectiveEndTime: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  linkUrl: [
    { required: true, message: '请输入链接地址', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序序号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  effectiveStartTime: [
    { required: false, message: '请选择生效开始时间', trigger: 'change' }
  ],
  effectiveEndTime: [
    { required: false, message: '请选择生效结束时间', trigger: 'change' }
  ]
}

// 上传地址（直接使用Write API地址，避免代理冲突）
const uploadAction = ref('http://localhost:5049/api/fileupload/carousel/upload')

// 图片上传成功
const handleUploadSuccess = (response: any, uploadFile: any) => {
  console.log('上传原始响应:', response);
  console.log('上传文件信息:', uploadFile);
  
  try {
    // Element Plus的el-upload组件返回的响应结构处理
    let actualResponse = response;
    
    // 如果是字符串，尝试解析JSON
    if (typeof response === 'string') {
      actualResponse = JSON.parse(response);
    }
    
    // 检查响应状态码
    if (actualResponse && actualResponse.code === 200 && actualResponse.data) {
      // 确保data对象存在url属性
      const imageUrl = typeof actualResponse.data === 'string' ? actualResponse.data : actualResponse.data.url;
      formData.imageUrl = imageUrl;
      ElMessage.success(actualResponse.message || '图片上传成功');
    } else {
      // 处理错误情况
      const errorMsg = actualResponse?.message || '图片上传失败';
      ElMessage.error(errorMsg);
      console.error('图片上传失败:', actualResponse);
    }
  } catch (error) {
    console.error('解析响应失败:', error);
    ElMessage.error('服务器响应格式错误');
  }
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构建请求数据 - 直接发送CarouselCreateDto格式
        const requestData = {
          title: formData.title,
          imageUrl: formData.imageUrl,
          linkUrl: formData.linkUrl || '',
          status: formData.status ? 1 : 0, // 转换为枚举值：1=Active(上架)，0=Inactive(下架)
          sort: formData.sortOrder || 1,
          description: '',
          // 确保日期格式为ISO字符串格式，或设置为null
          effectiveStartTime: formData.effectiveStartTime ? new Date(formData.effectiveStartTime).toISOString() : null,
          effectiveEndTime: formData.effectiveEndTime ? new Date(formData.effectiveEndTime).toISOString() : null
        }
        
        // 调试输出实际发送的数据
        console.log('发送的轮播图数据:', JSON.stringify(requestData, null, 2))
        
        const response = await carouselApi.create(requestData)
        
        if (response.code === 200) {
          ElMessage.success('轮播图添加成功')
          router.push('/content/carousel')
        } else {
          ElMessage.error(response.message || '添加失败')
        }
        
      } catch (error) {
        console.error('添加失败:', error)
        ElMessage.error('添加失败，请重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 取消操作
const handleCancel = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.carousel-add {
  padding: 20px;
  
  .page-header {
    margin-bottom: 32px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .form-container {
    background: white;
    border-radius: 8px;
    box-shadow: $box-shadow-base;
    padding: 40px;
    max-width: 800px;
    
    .carousel-form {
      .el-form-item {
        margin-bottom: 32px;
        
        .el-form-item__label {
          font-weight: 500;
          color: $text-color-primary;
          font-size: 14px;
        }
        
        .el-input {
          .el-input__wrapper {
            border-radius: 6px;
          }
        }
        
        .el-input-number {
          .el-input__wrapper {
            border-radius: 6px;
          }
          
          .el-input__inner {
            text-align: left;
          }
        }
      }
    }
    
    .upload-section {
      .image-uploader {
        .uploaded-image {
          width: 240px;
          height: 135px;
          object-fit: cover;
          border-radius: 8px;
          display: block;
          border: 1px solid $border-color-light;
        }
        
        .upload-area {
          width: 240px;
          height: 135px;
          border: 2px dashed $border-color;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s;
          background-color: #fafbfc;
          
          &:hover {
            border-color: $primary-color;
            background-color: #f0f7ff;
          }
          
          .upload-icon {
            font-size: 36px;
            color: #c0c4cc;
          }
        }
      }
      
      .upload-hint {
        margin-top: 12px;
        font-size: 12px;
        color: $text-color-secondary;
        line-height: 1.4;
      }
    }
    
    .sort-section {
      .sort-hint {
        margin-top: 12px;
        font-size: 12px;
        color: $text-color-secondary;
        line-height: 1.4;
      }
    }
    
    .form-actions {
      margin-top: 48px;
      display: flex;
      justify-content: center;
      gap: 16px;
      
      .el-button {
        min-width: 100px;
        border-radius: 6px;
      }
    }
  }
}

// Element Plus 组件样式覆盖
:deep(.el-upload-dragger) {
  padding: 0;
  border: none;
  border-radius: 8px;
  
  &:hover {
    border-color: transparent;
  }
}

:deep(.el-switch) {
  .el-switch__core {
    border-radius: 20px;
  }
}
</style>